package threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * # @File  : CachedThreadPool.java
 * # @Author: Lomo
 * # @Site  : lomo.space
 * # @Date  : 2021-09-01
 * # @Desc  : 可缓存线程池 newCachedThreadPool
 * 可缓存线程池，若线程池的容量超过了任务数，自动回收空闲线程，任务增加时可以自动添加新线程，线程池的容量不限制（动态化提供多线程资源的方式）
 *
 * 适用：执行很多短期的异步任务
 */
public class CachedThreadPool {
    private static ExecutorService cachedExecutor = Executors.newCachedThreadPool();

    // 测试方法
    private static void testCachedExecutor() {
        for (int i = 0; i < 6; i ++) {
            final int index = i;
            cachedExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    // run() 里执行调用我们需要多线程执行的任务/方法/函数
                    try {
                        System.out.println("sleep 2s ... ...");
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "index: " + index);
                }
            });
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("2s 后 ... ...");
        cachedExecutor.shutdown();
    }

    public static void main(String[] args) {
        testCachedExecutor();
    }
}
